package siena;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * This class provides the support for parsing and format dates.
 * @author jsanca
 *
 */
public class DateUtil {

	private static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") {
		private static final long serialVersionUID = 1L;
		{
			setTimeZone(TimeZone.getTimeZone("UTC"));
		}
	};
	
	private SimpleDateFormat simpleDateFormat = DEFAULT_DATE_FORMAT;
	
	
	
	
	/**
	 * Set a new format for the date.
	 * @param simpleDateFormat
	 */
	public void setDateFormat(String dateFormat) {
		
		if (null != dateFormat) {
			
		  this.simpleDateFormat = new SimpleDateFormat (dateFormat);
		  this.simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		}
	} // setDateFormat.
	
	/**
	 * Set a new time zone. 
	 * @param timeZone TimeZone.
	 */
	public void setTimeZone (TimeZone timeZone) {
		
		 this.simpleDateFormat.setTimeZone(timeZone);
	} // setTimeZone.


	/**
	 * Created a Date from a new String based in the dateFormat (see setDateFormat method).
	 * @param sDate String
	 * @return Date.
	 */
	public Date createDate (String sDate) {

		Date date = null;
		
		try {
			
			date =
				this.simpleDateFormat.parse(sDate);
		} catch (ParseException e) {

			throw new SienaException (e);
		}
		
		return date;
	} // createDate.
	
	/**
	 * Format the date based in the dateFormat (see setDateFormat method). 
	 * @param date Date
	 * @return String
	 */
	public String format (Date date) {
		
		return this.simpleDateFormat.format(date);
	} // format.
} // E:O:F:DateUtil.
